/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-10-8 上午11:24 Created by dwzhang
 */
package com.jade.bss.weixin.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jade.bss.weixin.WeixinApp;
import com.jade.bss.weixin.WeixinAppConfig;
import com.jade.bss.weixin.api.event.EventManager;
import com.jade.framework.base.context.ApplicationContextUtils;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 接收微信发送的消息和事件。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-10-8 上午11:24
 */
@Controller
@RequestMapping (value = "/weixin/message")
@Api(value = "微信-消息", description = "消息回调接口", hidden = true)
public class MessageController
{
    protected Log log = LogFactory.getLog(this.getClass());
    protected EventManager eventManager = ApplicationContextUtils.getBean("bss_weixinEventManager");
    protected WeixinAppConfig appConfig;

    public void setAppConfig(WeixinAppConfig appConfig)
    {
        this.appConfig = appConfig;
    }

    @RequestMapping (value = "/{appCode}")
    public void waiter(@PathVariable (value = "appCode") String appCode,
                       @RequestParam (value = "signature", required = false) String signature,
                       @RequestParam (value = "timestamp", required = false) String timestamp,
                       @RequestParam (value = "nonce", required = false) String nonce,
                       @RequestParam (value = "echostr", defaultValue = "") String echostr,
                       @RequestParam (value = "msg_signature", defaultValue = "") String msgSignature,
                       @RequestParam (value = "encrypt_type", defaultValue = "") String encryptType,
                       HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        WeixinApp app = appConfig==null?null:appConfig.getApp(appCode);
        if (StringUtils.equalsIgnoreCase(request.getMethod(), "GET")) {
            //todo 验证消息
            //boolean flag = SignUtils.checkSignature(app.getToken(), timestamp, nonce, signature);
            //返回成功
            PrintWriter printWriter = response.getWriter();
            printWriter.write(echostr);
            return;
        }

        //获取请求的内容
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String message = "", line;
        while ((line = br.readLine()) != null) {
            message += line;
        }
        log.info("receive message from weixin signature:" + signature + ",timestamp:" + timestamp + ",nonce:" +
                nonce + ",echostr:" + echostr + ",body:" + message);

        if (StringUtils.isBlank(encryptType)) {
            //明文模式
            //todo 验证消息
            //boolean flag = SignUtils.checkSignature(app.getToken(), timestamp, nonce, signature);
        }
        else {
            //安全模式
            //对消息进行解密
            WXBizMsgCrypt pc = new WXBizMsgCrypt(app.getToken(), app.getDesKey(), app.getAppId());
            message = pc.decryptMsg(msgSignature, timestamp, nonce, message);
        }

        //处理消息
        String result = eventManager.handleEvent(message);
        log.info("return to weixin:"+result);

        //返回响应
        PrintWriter printWriter = response.getWriter();
        printWriter.write(result);
    }
}
